/*
 * Project Name spring-boot-tools
 * File Name ConnectAction
 * Package Name com.huxiaosu.tools.cmpp.service.action
 * Create Time 2024/4/20
 * Create by name：liujie
 */
package com.huxiaosu.tools.cmpp.action;

import com.huxiaosu.tools.cmpp.enums.CommandId;
import com.huxiaosu.tools.cmpp.model.action.ConnectRespMsg;
import com.huxiaosu.tools.cmpp.utils.Length;
import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.buffer.IoBuffer;
import org.springframework.stereotype.Component;

/**
 * 7.4.1.1 CMPP_CONNECT 消息定义（SP -> ISMG）
 *
 * @author liujie
 * @date 2024/4/20 11:15
 */
@Slf4j
@Component
public class ConnectRespAction extends AbstractMessageAction {

    @Override
    public CommandId getMessageCommandId() {
        return CommandId.CMPP_CONNECT_RESP;
    }

    @Override
    public String getMessageCommandName() {
        return CommandId.CMPP_CONNECT_RESP.name();
    }

    @Override
    public ConnectRespMsg readMessage(IoBuffer ioBuffer) {
        ConnectRespMsg connectResp = new ConnectRespMsg();
        connectResp.setStatus(ioBuffer.getInt());
        byte[] ismg = new byte[Length.ConnectResp.AUTHENTICATOR_ISMG];
        ioBuffer.get(ismg);
        connectResp.setAuthenticatorISMG(ismg);
        connectResp.setVersion((byte)ioBuffer.getInt());
        return connectResp;
    }

    @Override
    public void execute() {
        log.info("< CMPP CONNECT RESP...>");
        ConnectRespMsg msgConnectResp = (ConnectRespMsg) super.message.getMessageHeader();
        int status = msgConnectResp.getStatus();
        log.info("< CMPP CONNECT RESP {} >",setStatus(status));
        if(status != 0){
            throw new RuntimeException(setStatus(status));
        }

    }
    public String setStatus(int status) {
        return switch (status) {
            case 0 -> "正确";
            case 1 -> "消息结构错";
            case 2 -> "非法源地址";
            case 3 -> "认证错";
            case 4 -> "版本太高";
            case 5 -> "其他错误";
            default -> status + ":未知";
        };
    }


}
